package com.example.sso.server.repository;

import com.example.sso.server.entity.Token;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Repository
public class TokenRepository {

    private final Map<String, Token> tokens = new HashMap<>();
    private final Map<String, String> codes = new HashMap<>();

    public String generateCode() {
        String code = UUID.randomUUID().toString().replace("-", "");
        codes.put(code, code);
        return code;
    }

    public boolean isValidCode(String code) {
        return codes.containsKey(code);
    }

    public void removeCode(String code) {
        codes.remove(code);
    }

    public Token generateToken() {
        String accessToken = UUID.randomUUID().toString().replace("-", "");
        Token token = new Token(accessToken, "user", 600, new Date());
        tokens.put(accessToken, token);
        return token;
    }

    public Token findByAccessToken(String accessToken) {
        return tokens.get(accessToken);
    }

    public boolean isValidToken(String accessToken) {
        Token token = tokens.get(accessToken);
        if (token == null) {
            return false;
        }
        long currentTime = System.currentTimeMillis();
        long expireTime = token.getCreateTime().getTime() + (token.getExpiresIn() * 1000);
        return currentTime < expireTime;
    }
}
    